package com.plusjun.gulimall.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.plusjun.common.utils.PageUtils;
import com.plusjun.common.utils.Query;
import com.plusjun.gulimall.product.dao.CategoryDao;
import com.plusjun.gulimall.product.entity.CategoryEntity;
import com.plusjun.gulimall.product.service.CategoryBrandRelationService;
import com.plusjun.gulimall.product.service.CategoryService;
import com.plusjun.gulimall.product.util.RedisUtil;
import com.plusjun.gulimall.product.vo.Catalog2VO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;


@Service("categoryService")
@Slf4j
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {
    @Resource
    CategoryBrandRelationService categoryBrandRelationService;

    @Resource
    RedisUtil redisUtil;
    @Resource
    RedisTemplate<String, Object> redisTemplate;

    @Resource
    RedissonClient redisson;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listWithTree() {
        // 1、查询出所有菜单分类数据
        List<CategoryEntity> entities = baseMapper.selectList(null);
        // 2、 将其组装成父子光系
        // 2.1)、使用Stream的API过滤出父级菜单和其子菜单
        List<CategoryEntity> entityList = entities.stream()
                // 将父级菜单过滤出来
                .filter(categoryEntity -> categoryEntity.getParentCid() == 0)
                // 映射出父级菜单的子菜单
                .map(menu -> {
                    // 设置关系
                    menu.setChildren(getChildren(menu, entities));
                    return menu;
                })
                .sorted((menu1, menu2) -> {
                    return (menu1.getSort() == null ? 0 : menu1.getSort())
                            - (menu2.getSort() == null ? 0 : menu2.getSort());
                })
                .collect(Collectors.toList());
        return entityList;
    }


    /**
     * @param root ： 当前分类元素
     * @param all  ： 所有的分类
     * @return
     */
    private List<CategoryEntity> getChildren(CategoryEntity root, List<CategoryEntity> all) {
        List<CategoryEntity> children = all.stream()
                // 过滤出同级分类
                .filter(categoryEntity -> Objects.equals(categoryEntity.getParentCid(), root.getCatId()))
                // 使用递归映射出所有分类的子菜单
                .map(categoryEntity -> {
                    categoryEntity.setChildren(getChildren(categoryEntity, all));
                    return categoryEntity;
                })
                // 菜单排序  getSort() 的返回值可能为null
                .sorted((menu1, menu2) -> {
                    return (menu1.getSort() == null ? 0 : menu1.getSort())
                            - (menu2.getSort() == null ? 0 : menu2.getSort());
                })
                .collect(Collectors.toList());
        return children;
    }

    @Override
    public void removeMenuByIds(List<Long> asList) {
        // TODO 检查当前删除的菜单，是否被别的地方引用
        baseMapper.deleteBatchIds(asList);
    }

    @Override
    public Long[] findCatelogPath(Long catelogId) {
        List<Long> path = new ArrayList<>();
        findParentPath(catelogId, path);
        Collections.reverse(path);
        return (Long[]) path.toArray(new Long[path.size()]);
    }

    private List<Long> findParentPath(Long catelogId, List<Long> path) {
        path.add(catelogId);
        CategoryEntity byId = this.getById(catelogId);
        if (byId.getParentCid() != 0) {
            findParentPath(byId.getParentCid(), path);
        }
        return path;
    }

    //@CacheEvict(value = "category",key = "'getLevel1Categorys'")
    /*@Caching(evict = {
            @CacheEvict(value = "category",key = "'getLevel1Categorys'"),
            @CacheEvict(value = "category",key = "'getCatelog2VO'")
    })*/
    @CacheEvict(value = "category",allEntries = true)
    @Transactional
    @Override
    public void updateCascade(CategoryEntity category) {
        // 更新自己表
        this.updateById(category);

        // 更新其他表
        if (!StringUtils.isEmpty(category.getName())) {
            // 更新关链表中的
            categoryBrandRelationService.updateCategory(category.getCatId(), category.getName());
        }

    }

    @Cacheable(value = {"category"},key = "#root.method.name")
    @Override
    public List<CategoryEntity> getLevel1Categorys() {
        System.out.println("查询数据库 getLevel1Categorys**********");
        List<CategoryEntity> list = this.list(new QueryWrapper<CategoryEntity>().eq("parent_cid", 0));
        return list;
    }

    @Cacheable(value = {"category"},key = "#root.method.name")
    @Override
    public Map<String, List<Catalog2VO>> getCatelog2VO(){
        System.out.println("********查询数据库 getCatelog2VO");
        List<CategoryEntity> selectList = baseMapper.selectList(null);
        // 拿到1级分类id
        List<CategoryEntity> level1Categorys = this.getParent_cid(selectList, 0L);
        Map<String, List<Catalog2VO>> listMap = level1Categorys.stream().collect(Collectors.toMap(item -> item.getCatId().toString(), item1 -> {
            List<CategoryEntity> categoryEntities = getParent_cid(selectList, item1.getCatId());
            List<Catalog2VO> catelog2VOList = null;
            if (categoryEntities != null) {
                // 封装 2 级分类
                catelog2VOList = categoryEntities.stream().map(item2 -> {
                    Catalog2VO catelog2VO = new Catalog2VO(item1.getCatId().toString(), null, item2.getCatId().toString(), item2.getName());
                    // 找当前分类的3级分类
                    List<CategoryEntity> catelogLevel3 = getParent_cid(selectList, item2.getCatId());
                    List<Catalog2VO.Catalog3VO> catelog3VOList = null;
                    if (catelogLevel3 != null) {
                        catelog3VOList = catelogLevel3.stream().map(item3 -> {
                            Catalog2VO.Catalog3VO catelog3VO = new Catalog2VO.Catalog3VO(item2.getCatId().toString(), item3.getCatId().toString(), item3.getName());
                            return catelog3VO;
                        }).collect(Collectors.toList());
                    }
                    catelog2VO.setCatalog3List(catelog3VOList);
                    return catelog2VO;
                }).collect(Collectors.toList());
            }
            return catelog2VOList;
        }));
        return listMap;
    }
    public Map<String, List<Catalog2VO>> getCatelog2VO1() {
        /**
         * 1、空结果缓存：解决缓存穿透问题
         * 2、设置过期时间（加随机值）：解决缓存雪崩
         * 3、加锁：解决缓存击穿问题
         */
        // 1、加入缓存
        //String getCatelog2VOFromCache = (String) redisUtil.get("catalogJSON");
        Map<String, List<Catalog2VO>> object = (Map<String, List<Catalog2VO>>) redisUtil.get("catalogJSON");
        if (Objects.isNull(object)) {
            System.out.println("*********缓存不命中！！！！查询数据库！！！！！！！！");
            //Map<String, List<Catalog2VO>> catelog2VOFromDB = getCatelog2VOFromDBWithLocalLock();
            Map<String, List<Catalog2VO>> catelog2VOFromDB = getCatelog2VOFromDBWithRedisLock();

            return catelog2VOFromDB;
        }
        System.out.println("*********缓存命中***************");
        /*Map<String, List<Catalog2VO>> object = JSON.parseObject(getCatelog2VOFromCache,
                new TypeReference<Map<String, List<Catalog2VO>>>() {});*/

        return object;
    }

    /**
     * 使用redis做分布式锁
     *
     * @return
     */
    public Map<String, List<Catalog2VO>> getCatelog2VOFromDBWithRedisLock() {
        // 锁的名字时区分锁的关键
        RLock lock = redisson.getLock("catalogJson-lock");
        lock.lock();
        Map<String, List<Catalog2VO>> dataFromDB = null;
        try {
            dataFromDB = getDataFromDB();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
        return dataFromDB;

    }

    public Map<String, List<Catalog2VO>> getCatelog2VOFromDBWithRedisLock1() {
        // 1、栈分布式锁，去redis占坑
        String uuid = UUID.randomUUID().toString();
        Boolean lock = redisTemplate.opsForValue().setIfAbsent("lock", uuid, 300, TimeUnit.SECONDS);
        if (lock) {
            System.out.println("*********加锁成功****");
            // 执行业务逻辑
            Map<String, List<Catalog2VO>> dataFromDB;
            try {
                dataFromDB = getDataFromDB();
            } finally {
                String script = "if redis.call('get',KEYS[1]) == ARGV[1] then return redis.call('del',KEYS[1]) else return 0 end";
                redisTemplate.execute(new DefaultRedisScript<Long>(script, Long.class),
                        Arrays.asList("lock"), uuid);
            }
            return dataFromDB;
        } else {
            System.out.println("加锁失败，/(ㄒoㄒ)/~~，重试");
            try {
                TimeUnit.MILLISECONDS.sleep(300);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            // 自旋
            return getCatelog2VOFromDBWithRedisLock();
        }

    }

    /**
     * 使用本地锁
     *
     * @return
     */
    public Map<String, List<Catalog2VO>> getCatelog2VOFromDBWithLocalLock() {
        synchronized (this) {
            Map<String, List<Catalog2VO>> object = (Map<String, List<Catalog2VO>>) redisUtil.get("catalogJSON");
            if (!Objects.isNull(object)) {
                return object;
            }

            /**
             *  1、将数据库中的多次查询变为一次查询
             *
             */
            return getDataFromDB();
        }

    }

    private Map<String, List<Catalog2VO>> getDataFromDB() {
        Map<String, List<Catalog2VO>> object = (Map<String, List<Catalog2VO>>) redisUtil.get("catalogJSON");
        if (!Objects.isNull(object)) {
            return object;
        }
        System.out.println("============查询数据库========");
        /**
         *  1、将数据库中的多次查询变为一次查询
         *
         */
        List<CategoryEntity> selectList = baseMapper.selectList(null);
        // 拿到1级分类id
        List<CategoryEntity> level1Categorys = this.getParent_cid(selectList, 0L);
        Map<String, List<Catalog2VO>> listMap = level1Categorys.stream().collect(Collectors.toMap(item -> item.getCatId().toString(), item1 -> {
            List<CategoryEntity> categoryEntities = getParent_cid(selectList, item1.getCatId());
            List<Catalog2VO> catelog2VOList = null;
            if (categoryEntities != null) {
                // 封装 2 级分类
                catelog2VOList = categoryEntities.stream().map(item2 -> {
                    Catalog2VO catelog2VO = new Catalog2VO(item1.getCatId().toString(), null, item2.getCatId().toString(), item2.getName());
                    // 找当前分类的3级分类
                    List<CategoryEntity> catelogLevel3 = getParent_cid(selectList, item2.getCatId());
                    List<Catalog2VO.Catalog3VO> catelog3VOList = null;
                    if (catelogLevel3 != null) {
                        catelog3VOList = catelogLevel3.stream().map(item3 -> {
                            Catalog2VO.Catalog3VO catelog3VO = new Catalog2VO.Catalog3VO(item2.getCatId().toString(), item3.getCatId().toString(), item3.getName());
                            return catelog3VO;
                        }).collect(Collectors.toList());
                    }
                    catelog2VO.setCatalog3List(catelog3VOList);
                    return catelog2VO;
                }).collect(Collectors.toList());
            }
            return catelog2VOList;
        }));
        //String s = JSON.toJSONString(listMap);
        redisUtil.set("catalogJSON", listMap, 60 * 60 * 24L);
        return listMap;
    }

    private List<CategoryEntity> getParent_cid(List<CategoryEntity> selectList, Long parent_cid) {
        List<CategoryEntity> list = selectList.stream()
                .filter(item -> Objects.equals(item.getParentCid(), parent_cid))
                .collect(Collectors.toList());
        return list;
    }


}